package com.hb.medical_research_system.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hb.medical_research_system.common.JWTUtils;
import com.hb.medical_research_system.common.Results;
import com.hb.medical_research_system.common.UserThreadLocal;
import com.hb.medical_research_system.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class JWTInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        if(handler instanceof HandlerMethod)
        log.info("拦截器生效");
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {  //token为空返回错误
            response.setContentType("application/json; charset=UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            String result = objectMapper.writeValueAsString(Results.info(Results.ERROR,"token为空"));
            response.getWriter().print(result);
//            2
//            Results results = new Results(0,"token为空");
//            response.setContentType("application/json; charset=UTF-8");
//            response.getWriter().print(JSON.toJSONString(results));
            return false;
        }

        String msg = "";

        try {  //解析
            boolean bool = JWTUtils.checkToken(token);
            if(bool){
                //通过,创建用户本地线程
                User user = JWTUtils.checkJwtToken(token);
                UserThreadLocal.put(user);
                log.info("token验证通过");
                return true;
            }
        } catch (SignatureVerificationException e){
            msg= "无效签名";
        }catch (TokenExpiredException e){
            msg= "已过期";
        }catch (AlgorithmMismatchException e){
            msg ="算法不一致";
        }catch (Exception e){
            msg="无效身份信息";
        }
        response.setContentType("application/json; charset=UTF-8");
        ObjectMapper objectMapper = new ObjectMapper();
        String result = objectMapper.writeValueAsString(Results.info(Results.ERROR, msg));
        response.getWriter().print(result);
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("----------结束本地线程----------");
        UserThreadLocal.remove();
    }
}
